package com.ccp.dev.system.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.*;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.consts.FileManagementContants;
import com.ccp.dev.system.model.*;
import com.ccp.dev.system.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * file_management 信息操作处理控制器
 *
 * @author zhaowj
 * @date 2020-03-22 14:11:51
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(ownermodel = SysAuditModelType.SYSTEM_SETTING)
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_SYSTEM + "/fileManagement")
public class FileManagementController extends SysBaseController {
    @Resource
    private FileManagementService fileManagementService;
    @Resource
    private FileManagementPermissionService fileManagementPermissionService;
    @Resource
    private FileManagementSquaredService fileManagementSquaredService;

    @Autowired
    private SysPropertyService sysPropertyService;


    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: zhaowj
     * @date: 2020-03-22 14:11:51
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到file_management首页", exectype = "页面跳转日志")
    public String viewList(ModelMap modelMap) {
        //获取按钮权限数据
        Map<String, Boolean> managePermission = fileManagementPermissionService.getPermissionMap();
        modelMap.put("parentType", FileManagementContants.PARENT_TYPE_TREE);
        modelMap.put("managePermission", managePermission);
        return "fileManagement/list";
    }

    /**
     * 功能描述: 跳转到添加为菜单页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/nodeList")
    @Action(description = "跳转到添加为菜单页面", exectype = "页面跳转日志")
    public String nodeList() {
        return "fileManagement/nodeList";
    }

    /**
     * 节点添加为菜单
     *
     * @param request  请求
     * @param modelMap 返回的map
     * @return 页面地址
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/listMenu")
    @Action(description = "节点添加为菜单", exectype = "页面跳转日志")
    public String listMenu(HttpServletRequest request, ModelMap modelMap) {
        String folderId = RequestUtil.getString(request, "parentId");
        String topFolderId = request.getParameter("topFolderId");
        //先查询文件夹是否存在
        FileManagement folder = fileManagementService.getOneById(folderId);
        if (null != folder) {
            QueryFilter queryFilter = new QueryFilter(request, false);
            queryFilter.addFilter("parentId", folderId);
            String basePath = getBasePath(request);
            //查询选中节点下的数据
            List<FileManagement> fileList = fileManagementService.getFilesPageByParentId(basePath, folder.getParentType(), queryFilter);
            //获取按钮权限数据
            Map<String, Boolean> managePermission = fileManagementPermissionService.getPermissionMap();
            modelMap.put("fileManagementList", fileList);
            modelMap.put("folderId", folderId);
            modelMap.put("parentType", folder.getParentType());
            modelMap.put("parentId", folderId);
            modelMap.put("managePermission", managePermission);
            modelMap.put("topFolderId", topFolderId);
        }
        return "fileManagement/listMenu";
    }

    /**
     * 节点添加为菜单
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @Action(description = "节点添加为菜单", exectype = "页面跳转日志")
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/dataList")
    public String dataList(HttpServletRequest request, ModelMap modelMap) {
        String folderId = RequestUtil.getString(request, "parentId");
        //先查询文件夹是否存在
        FileManagement folder = fileManagementService.getOneById((folderId));
        if (null != folder) {
            QueryFilter queryFilter = new QueryFilter(request, true);
            queryFilter.addFilter("parentId", folderId);
            String basePath = getBasePath(request);
            //查询选中节点下的数据
            List<FileManagement> fileList = fileManagementService.getFilesPageByParentId(basePath, folder.getParentType(), queryFilter);
            //获取按钮权限数据
            Map<String, Boolean> managePermission = fileManagementPermissionService.getPermissionMap();
            modelMap.put("fileManagementList", fileList);
            modelMap.put("folderId", folderId);
            modelMap.put("parentType", folder.getParentType());
            modelMap.put("parentId", folderId);
            modelMap.put("managePermission", managePermission);
        }
        return "fileManagement/menu";
    }

    /**
     * 跳转到九宫格页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/squared")
    @Action(description = "九宫格页面")
    public String squared(HttpServletRequest request, Model model){
        //查询文件
        String fileName = request.getParameter("fileName");
        String parentId = request.getParameter("parentId");
        String parentType = request.getParameter("parentType");
        //获取顶部面包屑排序
        LinkedList<FileManagementSquared> crumb = new LinkedList<>();
        if (parentId != null) {
            getCrumb(parentId, crumb);
            //倒序排列
            Collections.reverse(crumb);
        }
        //获取文件列表
        String basePath = getBasePath(request);
        List<FileManagementSquared> fileList = new ArrayList<>();
        //如果为空 代表全局搜索
        if (StringUtil.isEmpty(parentId)) {
            //获取当前用户可以查看的目录信息
            List<Map<String, Object>> viewList = fileManagementService.getFolderTree(Integer.parseInt(parentType), basePath);
            for (Map<String, Object> map : viewList) {
                String newParentId = map.get("id").toString();
                List<FileManagementSquared> itemList = fileManagementSquaredService.getFilesByParam(parentType, newParentId, fileName, basePath);
                fileList.addAll(itemList);
            }
        } else {
            fileList = fileManagementSquaredService.getFilesByParam(parentType, parentId, fileName, basePath);
        }
        if (fileList != null && fileList.size() > 0) {
            for (int i = 0; i < fileList.size(); i++) {
                FileManagementSquared fileManagementGetFileType = fileList.get(i);
                if (fileManagementGetFileType.getFileType() == 1) {
                    String id = fileManagementGetFileType.getId();
                    List<FileManagementSquared> childFiles = fileManagementSquaredService.getFilesByParam(parentType, id, "", basePath);
                    fileList.get(i).setChildFiles(childFiles);
                }
            }
        }
        model.addAttribute("fileList", fileList)
                .addAttribute("parentId", parentId)
                .addAttribute("crumb", crumb)
                .addAttribute("fileName", fileName == null ? "" : fileName)
                .addAttribute("parentType", parentType);
        return "/fileManagement/squared";
    }


    /**
     * 跳转到九宫格页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/squaredMenu")
    @Action(description = "九宫格菜单页面")
    public String squaredMenu(HttpServletRequest request, Model model){
        //查询文件
        String fileName = request.getParameter("fileName");
        String parentId = request.getParameter("parentId");
        String topFolderId = request.getParameter("topFolderId");
        String parentType = request.getParameter("parentType");
        //获取顶部面包屑排序
        LinkedList<FileManagementSquared> crumb = new LinkedList<>();
        if (parentId != null) {
            getCrumbMenu(parentId, crumb, topFolderId);
            //倒序排列
            Collections.reverse(crumb);
        }
        String basePath = getBasePath(request);
        List<FileManagementSquared> fileList = fileManagementSquaredService.getFilesByParam(parentType, parentId, fileName, basePath, topFolderId);
        if (fileList != null && fileList.size() > 0) {
            for (int i = 0; i < fileList.size(); i++) {
                FileManagementSquared fileManagementGetFileType = fileList.get(i);
                if (fileManagementGetFileType.getFileType() == 1) {
                    String id = fileManagementGetFileType.getId();
                    List<FileManagementSquared> childFiles = fileManagementSquaredService.getFilesByParam(parentType, id, "", basePath);
                    fileList.get(i).setChildFiles(childFiles);
                }
            }
        }
        model.addAttribute("fileList", fileList)
                .addAttribute("parentId", parentId)
                .addAttribute("crumb", crumb)
                .addAttribute("fileName", fileName == null ? "" : fileName)
                .addAttribute("parentType", parentType)
                .addAttribute("topFolderId", topFolderId == null ? "" : topFolderId);
        return "/fileManagement/squaredMenu";
    }

    /**
     * 跳转到文件映射页面
     *
     * @return 页面地址
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/mapping")
    @Action(description = "文件映射页面", exectype = "页面跳转日志")
    public String mapping() {
        return "fileManagement/mapping";
    }

    /**
     * 跳转到上传文件页面
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/file")
    @Action(description = "上传文件页面", detail = "跳转到上传文件页面<#if fl>成功<#else>失败</#if>")
    public String file(HttpServletRequest request, ModelMap modelMap) {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //读取配置文件中的对应关系
        int[] fileSecretLevels = FileManagementContants.getFileSecretByUserSecret(sysUser.getPrivacyLevel());
        //用户只能选择用户密级以下的文件密级上传文件
        List<Map<String, Object>> fileSecretList = fileManagementService.getFileSecretDic(fileSecretLevels);
        modelMap = folderOrFile(request, modelMap);
        modelMap.put("fileSecretList", fileSecretList);
        String parentId = RequestUtil.getString(request, "parentId");
        FileManagement fileManagement = fileManagementService.getOneById(parentId);
        modelMap.put("parentId", parentId);
        modelMap.put("parentName", fileManagement.getFileName());
        return "fileManagement/file";
    }

    /**
     * 功能描述: 加载树
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: zhaowj
     * @date: 2020-03-22 14:11:51
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "加载树", detail = "加载树<#if success>成功<#else>失败</#if>")
    public Object list(HttpServletRequest request) {
        Map<String, Object> retMap = new HashMap<>();
        try {
            String basePath = getBasePath(request);
            int treeType = RequestUtil.getInt(request, "treeType");
            //获取按钮权限数据
            Map<String, Boolean> managePermission = fileManagementPermissionService.getPermissionMap();
            managePermission.put("del", true);
            retMap.put("treeList", fileManagementService.getFolderTree(treeType, basePath));
            retMap.put("managePermission", managePermission);
            retMap.put("parentType", treeType);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("query.success", retMap);
    }

    /**
     * 获取basePath
     */
    private String getBasePath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/";
        return basePath;
    }

    /**
     * 加载归类树数据
     */
    @RequestMapping("/mappingTree")
    @ResponseBody
    @Action(description = "加载归类树数据", detail = "加载归类树数据<#if success>成功<#else>失败</#if>")
    public Object mappingTree(HttpServletRequest request) {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String basePath = getBasePath(request);
        List<Map<String, Object>> list = fileManagementService.getFolderTree(FileManagementContants.PARENT_TYPE_LOGICTREE, basePath);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("query.success", list);
    }


    /**
     * 查看文件管理列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/fileManagementList")
    @ResponseBody
    @Action(description = "查看文件管理列表", detail = "查看文件管理列表<#if success>成功<#else>失败</#if>")
    public Object fileManagementList(HttpServletRequest request) {
        String parentId = request.getParameter("parentId") == null ? FileManagementContants.ROOT_PARENT_ID : RequestUtil.getString(request, "parentId");
        QueryFilter queryFilter = new QueryFilter(request, true);
        //若没有排序规则 则按名称排序
        if (queryFilter.get("orderField") == null) {
            queryFilter.addFilter("orderField", "file_name");
            queryFilter.addFilter("orderSeq", "asc");
        }
        //默认查询物理树中最早建的根节点下的列表数据
        if (parentId.equals(FileManagementContants.ROOT_PARENT_ID)) {
            parentId = fileManagementService.initPageList(parentId);
        }
        queryFilter.addFilter("parentId", parentId);
        int parentType = RequestUtil.getInt(request, "parentType") == 0 ? FileManagementContants.PARENT_TYPE_TREE : RequestUtil.getInt(request, "parentType");
        String basePath = getBasePath(request);
        Map<String, Object> retMap = new HashMap<>();
        try {
            //查询选中节点下的数据
            List<FileManagement> list = fileManagementService.getFilesPageByParentId(basePath, parentType, queryFilter);
            //如果目录的创建人是当前用户，则可以设置目录的权限
            boolean nodePermission = false;
            FileManagement fileManagement = fileManagementService.getOneById(parentId);
            if (null != fileManagement) {
                if (ContextUtil.getCurrentUserId().equals(fileManagement.getUploadPersonId())) {
                    nodePermission = true;
                }
            }
            //获取按钮权限数据
            Map<String, Boolean> managePermission = fileManagementPermissionService.getPermissionMap();
            retMap.put("fileManagementList", list);
            retMap.put("parentType", parentType);
            retMap.put("parentId", parentId);
            retMap.put("nodePermission", nodePermission);
            retMap.put("managePermission", managePermission);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("query.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), retMap);
    }

    /**
     * 文件映射
     */
    @RequestMapping("/addMapping")
    @ResponseBody
    @Action(description = "文件映射", execOrder = ActionExecOrder.AFTER, detail = "文件映射<#if success>成功<#else>失败</#if>")
    public Object addMapping(HttpServletRequest request) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] fileIds = RequestUtil.getStringAryByStr(request, "fileIds");
        String parentId = RequestUtil.getString(request, "parentId");
        String alias = RequestUtil.getString(request, "alias");
        String resultMsg = fileManagementService.addFileMapping(fileIds, parentId, alias);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("operation.success", resultMsg);
    }

    /**
     * 取消文件映射
     */
    @RequestMapping("/cancelMapping")
    @ResponseBody
    @Action(description = "取消文件映射", execOrder = ActionExecOrder.AFTER, detail = "取消文件映射<#if success>成功<#else>失败</#if>")
    public Object cancelMapping(HttpServletRequest request) {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] fileIds = RequestUtil.getStringAryByStr(request, "fileIds");
        fileManagementService.delByIdArray(fileIds);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("operation.success");
    }

    /**
     * 功能描述: 跳转到新建文件夹页面
     *
     * @return: java.lang.String
     * @auther: zhaowj
     * @date: 2020-03-22 14:11:51
     */
    @RequestMapping("/folder")
    @ResponseBody
    @Action(description = "获取新建文件夹需要的参数", detail = "获取新建文件夹需要的参数<#if success>成功<#else>失败</#if>")
    public Object viewAdd(HttpServletRequest request, ModelMap modelMap) {
        try {
            modelMap = folderOrFile(request, modelMap);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("operation.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("operation.success", modelMap);
    }


    /**
     * 跳转到新建文件夹和上传文件页面公共部分
     *
     * @param request
     * @return
     * @throws Exception
     */
    private ModelMap folderOrFile(HttpServletRequest request, ModelMap modelMap) {
        String parentId = RequestUtil.getString(request, "parentId");
        String parentType = RequestUtil.getString(request, "parentType");
        modelMap.put("selNodeId", RequestUtil.getString(request, "selNodeId"));
        modelMap.put("parentId", parentId);
        modelMap.put("treeType", parentType);
        return modelMap;
    }

    /**
     * 新建文件夹
     *
     * @param fileManagement 文件对象
     * @throws Exception
     */
    @RequestMapping("/addFolder")
    @ResponseBody
    @Action(description = "新建文件夹", execOrder = ActionExecOrder.AFTER, detail = "<#if fl>新增<#else>编辑</#if>文件夹")
    public Object addFolder(@RequestBody FileManagement fileManagement) {
        String resultMsg;
        String fileId = UUIDUtils.getUUIDFor32();
        try {
            String parentId = fileManagement.getParentId();
            fileManagement.setParentId(parentId);
            //如果父节点是0 代表现在要创建的是一个根节点
            if (parentId.equals(FileManagementContants.JSP_PARENT_ID)) {
                parentId = FileManagementContants.ROOT_PARENT_ID;
                //根节点的父节点统一为-1
                fileManagement.setParentId(parentId);
            }
            //判断文件夹名称是否重复
            String fileIsExist = fileManagementService.fileNameExist(fileManagement.getFileName(), parentId,
                    "", FileManagementContants.FILE_TYPE_FOLDER, "", "");
            if (fileIsExist.equals(FileManagementContants.FILE_REMANE_NAMEREPEAT)) {
                resultMsg = fileManagement.getFileName() + localeMessageSource.getMessage("fileManagement.existFolder");
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail(resultMsg);
            } else {
                fileManagement.setId(fileId);
                fileManagement.setFileType(FileManagementContants.FILE_TYPE_FOLDER);
                fileManagement.setFileSecretLevel(FileManagementContants.FILE_SECRET_PUBLIC);
                fileManagementService.addFileManagement(fileManagement);
                resultMsg = localeMessageSource.getMessage("fileManagement.newFolder.success");
            }
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("save.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(fileId, resultMsg);
    }

    /**
     * 修改文件夹
     *
     * @param fileManagement 文件对象
     */
    @RequestMapping("/editFolder")
    @ResponseBody
    @Action(description = "修改文件夹", execOrder = ActionExecOrder.AFTER, detail = "修改文件夹<#if success>新增<#else>编辑</#if>文件夹")
    public Object editFolder(@RequestBody FileManagement fileManagement) {
        String result;
        String message;
        SysAuditThreadLocalHolder.putParamerter("success", false);
        try {
            result = fileManagementService.editFolder(fileManagement);
        } catch (Exception e) {
            e.printStackTrace();
            return getResultDataError("update.failure");
        }
        if (FileManagementContants.FILE_REMANE_NO_FILE.equals(result)) {
            message = "fileManagement.noFile！";
            return getResultDataError(message);
        } else if (FileManagementContants.FILE_REMANE_SUCCESS.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
            message = "update.success";
        } else if (FileManagementContants.FILE_REMANE_NAMEREPEAT.equals(result)) {
            message = "fileManagement.duplicateFileName";
            return getResultDataError(message);
        } else {
            message = "update.failure";
            return getResultDataError(message);
        }
        return getResultDataSuccess(message);
    }

    /**
     * 修改文件 名称/摘要
     *
     * @param fileManagement 文件对象
     */
    @RequestMapping("/editFile")
    @ResponseBody
    @Action(description = "修改", execOrder = ActionExecOrder.AFTER, detail = "修改文件<#if success>新增<#else>编辑</#if>文件夹")
    public Object editFile(@RequestBody FileManagement fileManagement){
        String result;
        String message;
        try {
            result = fileManagementService.editFile(fileManagement);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            e.printStackTrace();
            return getResultDataError("update.failure");
        }
        if (FileManagementContants.FILE_REMANE_NO_FILE.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            message = "fileManagement.noFile！";

        } else if (FileManagementContants.FILE_REMANE_SUCCESS.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
            message = "update.success";
        } else if (FileManagementContants.FILE_REMANE_NAMEREPEAT.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            message = "fileManagement.duplicateFileName";
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            message = "update.failure";
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess(message);
    }

    /**
     * 跳转到文件编辑页面
     *
     * @param request 请求
     * @return 文件路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    @Action(description = "跳转到文件编辑页面", execOrder = ActionExecOrder.AFTER, detail = "跳转到文件编辑页面")
    public String edit(HttpServletRequest request, ModelMap modelMap) {
        // 获取当前用户
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        String fileId = RequestUtil.getString(request, "fileId");
        //读取配置文件中的对应关系
        int[] fileSecretLevels = FileManagementContants.getFileSecretByUserSecret(sysUser.getPrivacyLevel());
        //用户只能选择用户密级以下的文件密级上传文件
        List<Map<String, Object>> fileSecretList = fileManagementService.getFileSecretDic(fileSecretLevels);
        modelMap.put("fileId", fileId);
        modelMap.put("fileSecretList", fileSecretList);
        return "fileManagement/edit";
    }

    /**
     * 功能描述: 获取某个文件的信息
     *
     * @param: id 参数对象必须是"ID"
     * @return: java.lang.Object
     * @auther: zhaowj
     * @date: 2020-03-22 14:11:51
     */
    @RequestMapping("/getFile")
    @ResponseBody
    @Action(description = "获取某个文件的信息", detail = "获取某个文件的信息<#if success>成功<#else>失败</#if>")
    public Object get(HttpServletRequest request) {
        String fileId = RequestUtil.getString(request, "fileId");
        FileManagement fileManagement = fileManagementService.getOneById(fileId);
        if (null == fileManagement) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", fileManagement);
    }

    /**
     * 删除文件/文件夹
     *
     * @param fileIds 文件/文件夹ID 多个时用","隔开
     */
    @RequestMapping("/deleteFile")
    @ResponseBody
    @Action(description = "删除文件", execOrder = ActionExecOrder.AFTER, detail = "删除文件<#if success>成功<#else>失败</#if>")
    public Object deleteFile(String fileIds) throws Exception {
        String message;
        String result = fileManagementService.deleteFile(fileIds);
        if (FileManagementContants.DELETE_FILE_NO_FILE.equals(result)) {
            message = "delete.success";
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else if (FileManagementContants.DELETE_FILE_SUCCESS.equals(result)) {
            message = "delete.success";
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else if (FileManagementContants.DELETE_FILE_OTHER_USER_FILE.equals(result)) {
            message = "fileManagement.otherUserFile";
            SysAuditThreadLocalHolder.putParamerter("success", false);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            message = "delete.failure";
        }
        return getResultDataSuccess(message);
    }

    /**
     * 删除文件夹
     *
     * @param fileIds 文件夹ID 多个时用","隔开
     */
    @RequestMapping("/deleteFolder")
    @ResponseBody
    @Action(description = "删除文件夹", execOrder = ActionExecOrder.AFTER, detail = "删除文件夹")
    public Object deleteFolder(String fileIds) {
        String result;
        try {
            result = fileManagementService.deleteFile(fileIds);
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("fileManagement.delFolderFai");
        }
        if (FileManagementContants.DELETE_FILE_NO_FILE.equals(result) || FileManagementContants.DELETE_FILE_SUCCESS.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("fileManagement.delFolderSuccess");
        } else if (FileManagementContants.DELETE_FILE_OTHER_USER_FILE.equals(result)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("fileManagement.delContainOther");
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("fileManagement.delFolderFai");
        }
    }

    /**
     * 打包下载文件
     *
     * @param fileIds  需要下载的文件/文件夹ID
     * @param response
     */
    @RequestMapping("/downloadFile")
    @Action(description = "下载文件", execOrder = ActionExecOrder.AFTER, detail = "下载文件")
    public void downloadFile(String fileIds, HttpServletResponse response, HttpServletRequest request) throws
            Exception {
        String fileName = "";
        String[] allFileId = fileIds.split(",");
        if (allFileId.length > 1) {
            //若下载多个 则使用当前时间作为文件名
            Date day = new Date();
            String time = DateFormatUtil.formatDate(day);
            fileName = time + FileManagementContants.FILE_ZIP_FORMAT;
        } else {
            FileManagement fileManagement = fileManagementService.getOneById(fileIds);
            fileName = fileManagement.getFileName();
            //若下载文件夹则使用zip结尾
            if (fileManagement.getFileType() == FileManagementContants.FILE_TYPE_FOLDER) {
                fileName += FileManagementContants.FILE_ZIP_FORMAT;
            } else {
                fileName += "." + fileManagement.getFileFormat();
            }
        }
        String downloadFilePath = fileManagementService.downloadFile(fileIds);
        FileUtil.downLoadFile(request, response, downloadFilePath, fileName);
    }

    /**
     * 附件上传操作
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    @Action(description = "文件上传", exectype = "管理日志", detail = "上传文件<#if success>成功<#else>失败</#if>" + "<#list fileManagement as item>" + "【${item.fileName}】" + "</#list>")
    public Object fileUpload(MultipartHttpServletRequest request) {
        String errorMessage = "";
        try {
            int fileSecretLevel = RequestUtil.getInt(request, "fileSecretLevel");
            String fileKeywords = RequestUtil.getString(request, "fileKeywords");
            String parentId = RequestUtil.getString(request, "parentId");
            // 获取当前用户
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            // 附件保存路径
            String attachPath = SysFileService.getBasePath();
            FileManagement fileManagement = new FileManagement();
            fileManagement.setFileKeywords(fileKeywords);
            fileManagement.setFileSecretLevel(fileSecretLevel);
            fileManagement.setParentId(parentId);
            fileManagement.setParentType(FileManagementContants.PARENT_TYPE_TREE);
            Map<String, MultipartFile> files = request.getFileMap();
            Iterator<MultipartFile> it = files.values().iterator();

            SysProperty sysProperty = sysPropertyService.getOneById(FileManagementContants.FILE_UPLOAD_TYPE);
            String allowFileType = sysProperty.getPropertyValue();
            while (it.hasNext()) {
                MultipartFile f = it.next();
                String oriFileName = f.getOriginalFilename();
                try {
                    String fileId = UUIDUtils.getUUIDFor32();
                    String extName = FileUtil.getFileExt(oriFileName);
                    if(!allowFileType.contains(extName)){
                        errorMessage = localeMessageSource.getMessage("fileManagement.uploadType.fail")+allowFileType;
                        return fail(errorMessage);
                    }
                    String fileName = fileId + "." + extName;
                    //判断文件名是否重复
                    String name = oriFileName.substring(0, oriFileName.lastIndexOf('.'));
                    String fileIsExist = fileManagementService.fileNameExist(name, parentId, extName, FileManagementContants.FILE_TYPE_FILE, "", "");
                    if (fileIsExist.equals(FileManagementContants.FILE_REMANE_NAMEREPEAT)) {
                        errorMessage = localeMessageSource.getMessage("fileManagement.uploadFileFail");
                    } else {
                        // 开始写入物理文件
                        String filePath = createFilePath(attachPath + File.separator, fileName);
                        String fileP = filePath.replace(attachPath + File.separator, "");
                        //先写文件，再压缩
                        FileUtils.copyInputStreamToFile(f.getInputStream(), new File(filePath));
                        String filePassword = SysFile.PASSWORD_PROJECT_NAME + "_" + sysUser.getAccount() + "_" + fileId;
                        ZipUtil.zipSetPass(filePath, true, filePassword, SysFile.ENCRYPT_FILE_SUR_FIX);
                        //需要把原来的文件后缀进行替换
                        fileP = fileP.split("\\.")[0] + "." + SysFile.ENCRYPT_FILE_SUR_FIX;
                        //保存相对路径
                        fileManagement.setFileStorge(fileP);
                        // 向数据库中添加数据
                        fileManagement.setId(fileId);
                        // 附件名称
                        fileManagement.setFileName(name);
                        fileManagement.setFileType(FileManagementContants.FILE_TYPE_FILE);
                        fileManagement.setFileFormat(extName);
                        //文件大小
                        fileManagement.setFileSize(FileUtil.getSize(f.getSize()));
                        // 字节总数
                        fileManagement.setTotalBytes(f.getSize());
                        fileManagementService.addFileManagement(fileManagement);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    errorMessage = localeMessageSource.getMessage("file.upload.failure");
                    SysAuditThreadLocalHolder.putParamerter("success", false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("file.upload.failure");
        }
        if (StringUtil.isNotEmpty(errorMessage)) {
            return fail(errorMessage);
        }
        //返回前台json数据
        return getResultDataSuccess("file.upload.success");
    }

    /**
     * 创建文件目录
     *
     * @param tempPath 临时路径
     * @param fileName 文件名称
     * @return 文件的完整目录
     */
    private static String createFilePath(String tempPath, String fileName) {
        File one;
        Calendar cal = Calendar.getInstance();
        // 当前年份
        Integer year = cal.get(Calendar.YEAR);
        Date d = new Date();
        //当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowDate = sdf.format(d);
        one = new File(tempPath + File.separator + year + File.separator + nowDate);
        if (!one.exists()) {
            one.mkdirs();
        }
        return one.getPath() + File.separator + fileName;
    }

    /**
     * 接口：通过文件夹id，获取其下的所有文件信息
     *
     * @param folderId 文件夹id
     * @return 返回JSON 数据
     * @throws Exception
     */
    @RequestMapping("/getFileList_{folderId}")
    @ResponseBody
    @Action(description = "通过文件夹id，获取其下的所有文件json信息", detail = "获取其下的所有文件json信息<#if success>成功<#else>失败</#if>")
    public Object getListByFolderId(@PathVariable("folderId") String folderId) {
        try {
            //先查询文件夹是否存在
            FileManagement folder = fileManagementService.getOneById(folderId);
            if (null == folder) {
                return getResultDataError("fileManagement.queryNoFolder");
            }
            SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
            int[] fileSecretLevels = FileManagementContants.getFileSecretByUserSecret(sysUser.getPrivacyLevel());
            List<FileManagement> fileList = fileManagementService.getFilesByParentIdAndSecret(folderId, fileSecretLevels);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            return getResultDataSuccess("operation.success", fileList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("fileManagement.failure");
        }
    }

    /**
     * 递归获取面包屑导航
     *
     * @param parentId 父级目录ID
     * @param crumb    面包屑列表
     */
    private LinkedList<FileManagementSquared> getCrumbMenu(String parentId, LinkedList<FileManagementSquared> crumb, String topFolderId) {
        FileManagementSquared file = fileManagementSquaredService.getOneById(parentId);
        if (!parentId.equals(topFolderId) && file != null) {
            String pId = file.getParentId();
            crumb.add(file);
            getCrumbMenu(pId, crumb, topFolderId);
        }
        return crumb;
    }

    /**
     * 递归获取面包屑导航
     *
     * @param parentId 父级目录ID
     * @param crumb    面包屑列表
     */
    private LinkedList<FileManagementSquared> getCrumb(String parentId, LinkedList<FileManagementSquared> crumb) {
        FileManagementSquared fileById = fileManagementSquaredService.getOneById(parentId);
        if (fileById != null) {
            String pId = fileById.getParentId();
            crumb.add(fileById);
            getCrumb(pId, crumb);
        }
        return crumb;
    }
}
